<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\skits;


use app\common\model\app\App;
use app\common\model\skits\Skits;
use app\common\model\skits\SkitsEpisodes;
use app\common\logic\BaseLogic;
use app\common\service\douyin\DouyinService;
use app\common\service\video\OssVideoService;
use app\common\service\video\VideoService;
use app\common\service\wechat\WechatService;
use think\facade\Db;
use think\facade\Log;


/**
 * SkitsEpisodes逻辑
 * Class SkitsEpisodesLogic
 * @package app\adminapi\logic
 */
class SkitsEpisodesLogic extends BaseLogic
{


    /**
     * 上传视频
     *
     * @param array $params
     * @return bool|string
     */
    public static function add(array $params)
    {
        ini_set('memory_limit', '2048M');
        set_time_limit(300);
        $skitsId  = $params['skits_id'] ?? 0;
        $videos   = $params['videos'] ?? [];
        $compress = $params['compress'] ?? 100;
        $clarity  = $params['clarity'] ?? 1;

        foreach ($videos as $video) {
            $result = VideoService::uploadVideo($video, $skitsId, (int)$compress, (int)$clarity);
            Log::write('上传剧集：' . json_encode($result), 'info', $result);
            $err = $result['err'] ?? -1;
            $msg = $result['msg'] ?? '上传视频失败';
            if ($err != 0) {

                return $msg;
            }
        }

        return true;
    }


    /**
     * 上传剧集到微信、抖音
     *
     * @param $params
     * @return bool|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function uploadEpisodes($params)
    {
        $appId       = $params['app_id'] ?? '';
        $skitsId     = $params['skits_id'] ?? 0;
        $episodesIds = $params['episodes_ids'] ?? [];
        if (!$appId || !$skitsId || !$episodesIds) {

            return false;
        }
        $app      = App::find($appId);
        $skits    = Skits::find($skitsId);
        $episodes = SkitsEpisodes::whereIn('id', $episodesIds)->order('episodes_order', 'asc')->select();

        $fails = [];
        switch ($app->channel) {
            case 1:
                foreach ($episodes as $episode) {
                    $title    = $skits->skits_name . '-' . $episode->episodes_name;
                    $videoUrl = OssVideoService::getVideoUrl($skitsId, $episode->episodes_order, $episode->episodes_path);
                    if (!$videoId = DouyinService::uploadVideo($app->app_id, $videoUrl, $title, 'm3u8')) {
                        $fails[] = $episode->episodes_name . '上传失败，请重新上传';
                    }
                    $episode->douyin_media_id = $videoId;
                    $episode->save();
                }
                break;
            case 2 :
                foreach ($episodes as $episode) {
                    if ($episode->wechat_media_id) {
                        continue;
                    }
                    $mediaName = $skits->skits_name . ' - ' . $episode->episodes_name;
                    $mediaUrl  = OssVideoService::getVideoUrl($skitsId, $episode->episodes_order, $episode->episodes_path);
                    if (!WechatService::pullUpload($appId, $mediaName, $mediaUrl)) {
                        $fails[] = $episode->episodes_name . '上传失败，请重新上传';
                    }
                }
                break;
        }

        if (empty($fails)) {

            return true;
        }

        return implode("\r\n", $fails);
    }


    /**
     * 删除剧集
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function deleteEpisodes($params)
    {
        $appId      = $params['app_id'] ?? '';
        $mediaId    = $params['media_id'] ?? '';
        $episodesId = $params['episodes_id'] ?? 0;

        if (!$appId || !$episodesId) {

            return false;
        }
        $app      = App::find($appId);
        $episodes = SkitsEpisodes::find($episodesId);

        switch ($app->channel) {
            case 1:
                $episodes->douyin_media_id = '';

                return $episodes->save();
            case 2 :
                $episodes->wechat_media_id = '';
                $episodes->save();
                return WechatService::deleteMedia($appId, $mediaId);
            default:
                return false;
        }
    }


    public function uploadDouyinEpisodes($params)
    {

    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/13 15:05
     */
    public static function delete(array $params): bool
    {
        return SkitsEpisodes::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/13 15:05
     */
    public static function detail($params): array
    {
        return SkitsEpisodes::findOrEmpty($params['id'])->toArray();
    }
}
